import Router from '../../utils/router';
import base from '../../config/base.js';
import service from '../../services/collage';
import Record from '../../utils/page-record.js';
var scrollTime = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    icon_play: base.static + 'store/play2.png',
    icon_free: base.static + 'collage/free2.png',
    icon_myFree: base.static + 'collage/myFree1.png',
    icon_next: base.static + 'collage/next.png',
    icon_mask_sellout: base.static + 'collage/out.png',
    icon_fail: base.static + 'collage/fail.png',
    icon_noorder: base.static + '/collage/no-order-list.png',
    icon_no_avater: base.static + '/free/head.png',
    store_id: '',
    user_info: '',
    current: 1, //当前选项卡
    canTake: null, //可以领取弹窗
    canTakeTimes: 1,
    goodsList: [], //免费拿
    endFreeBloon: true,
    loadFreeBloon: true,
    pageFree: '',
    orderlist: [], //我的免费拿
    endOrderBloon: true,
    loadOrderBloon: true,
    pageOrder: '',
    nomoreFree: true,
    nomoreOrder: true,
    swiperList: '', //免费拿轮播
    clickTimes: 1, //我的免费拿点击次数
    isShenhe: '', //审核开关
    hottodyList: [], // 2.12.0今日热销
    pageHot: 0,
    endHotBloon: true,
    loadHotBloon: true,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let user_info = wx.getStorageSync('user_info')
    that.setData({
      store_id: user_info.lastView.seid,
      user_info: user_info,
      isShenhe: wx.getStorageSync('isShenhe')
    })
    if (options.method && options.method == 'navigateBack'){
    }else{
      that.getFreeList(1);
      that.swiperCollage();
    }
    
  },
  // 更改拼团id
  changeId: function(e){
    let that = this;
    let param = {};
    let inx = e.detail.inx;
    let strings = "goodsList[" + inx + "].ceorid"
    param[strings] = e.detail.ceorid;
    that.setData(param);
  },
  // 免费拿轮播
  swiperCollage: function(){
    let that = this;
    let params = {}
    service.collage(params, function (res) {
      if (res.code && res.code == 200) {
        that.setData({
          swiperList: res.data.dataList
        })
      }
    });
    wx.stopPullDownRefresh()
  },
  //免费拿列表
  getFreeList: function (page) {
    let that = this;
    let params = {
      page: page,
      offset: 10
    }
    service.collagegoodslist(params, function (res) {
      if (res.code && res.code == 1) {
        let stolist = that.data.goodsList.concat(res.data.list);
        that.setData({
          goodsList: stolist,
          pageFree: page + 1,
          canTake: res.data.can_change,
          endFreeBloon: true
        })
        if (stolist.length >= res.data.count) {
          that.setData({
            loadFreeBloon: false,
          })
          that.storeListHot(1)
        }
      }
    });
    wx.stopPullDownRefresh()
  },
  // 今日热销列表
  storeListHot: function (page) {
    let that = this;
    let params = {
      page: page,
      per_page: 10
    }
    service.customerRecommend(params, function (res) {
      if (res && res.code == 200) {
        let stolistHot = that.data.hottodyList.concat(res.data.recommend);
        that.setData({
          hottodyList: stolistHot,
          pageHot: page + 1,
          endHotBloon: true
        });
        //是否到底
        if (stolistHot.length == res.data.count) {
          that.setData({
            loadHotBloon: false,
            nomoreFree: false,
          })
        }
      }
      wx.stopPullDownRefresh();
    });
  },
  //我的免费拿订单列表
  collageorderlist(page){
    let that = this;
    let params = {
      limit: 10,
      offset: page
    }
    service.collageorderlist(params,function(res){
      if(res && res.code == 1){
        let orderlist = that.data.orderlist.concat(res.data.data);
        that.setData({
          orderlist: orderlist,
          pageOrder: page + 1,
          endOrderBloon: true,
        })
        if (orderlist != ""){
          for (let i = 0; i < orderlist.length; i++){
            orderlist[i].timmer = null;
            if (orderlist[i].order_status == 1){
              let current_time_str = res.data.current_time.replace(/-/g, "/");
              let end_time_str = orderlist[i].end_time.replace(/-/g, "/");
              let current_times = new Date(current_time_str).getTime();
              let end_time = new Date(end_time_str).getTime();
              let remaining_time = end_time - current_times
              that.getremainingtime(remaining_time, orderlist[i],i)
            }
          }
        }
        if (orderlist.length >0 && orderlist.length >= res.data.total_num) {
          that.setData({
            nomoreOrder: false,
            loadOrderBloon: false,
          })
        }
      }
      wx.stopPullDownRefresh()
    })
  },
  //获取剩余时间方法
  getremainingtime(remaining_time,item,i){
    let that = this;
    item.timmer = setTimeout(function () {
      if (remaining_time <= 0) {
        let param = {}
        let houstr = "orderlist[" + i + "].hours"
        let minstr = "orderlist[" + i + "].minutes"
        let secstr = "orderlist[" + i + "].seconds"
        let status = "orderlist[" + i + "].order_status"
        item.hours = 0
        item.minutes = 0
        item.seconds = 0
        param[houstr] = "0";
        param[minstr] = "0";
        param[secstr] = "0";
        param[status] = 4;
        that.setData(param);
        clearTimeout(item.timmer);
      } else {
        remaining_time = remaining_time - 1000;
        let param = {}
        let houstr = "orderlist[" + i + "].hours"
        let minstr = "orderlist[" + i + "].minutes"
        let secstr = "orderlist[" + i + "].seconds"
        let status = "orderlist[" + i + "].order_status"
        item.hours = parseInt(remaining_time / 1000 / 60 / 60);
        item.minutes = parseInt(remaining_time / 1000 / 60 % 60);
        item.seconds = parseInt(remaining_time / 1000 % 60);
        param[houstr] = parseInt(remaining_time / 1000 / 60 / 60);
        param[minstr] = parseInt(remaining_time / 1000 / 60 % 60);
        param[secstr] = parseInt(remaining_time / 1000 % 60);
        that.setData(param);
        if (item.timmer){
          that.getremainingtime(remaining_time, item, i)
        }
      }
    }, 1000);
  },
  // 立即使用
  useBtn: function(){
    let that = this;
    that.setData({
      canTake: null,
      icon_free: base.static + 'collage/free1.png',
      icon_myFree: base.static + 'collage/myFree2.png',
      current: 2,
      canTakeTimes: 2,
      clickTimes: 2,
    })
    that.collageorderlist(1)
  },
  // 点击底部选项卡
  chooseTab: function(e){
    let that = this;
    let current = e.currentTarget.dataset.curt;
    if (current == 1){
      that.setData({
        icon_free: base.static + 'collage/free2.png',
        icon_myFree: base.static + 'collage/myFree1.png',
        current: current,
      })
      that.data.orderlist.forEach((item, index) => { //清除定时器
        if (item.timmer) {
          clearTimeout(item.timmer)
        }
      })
      that.setData({
        orderlist: [], //我的免费拿
        endOrderBloon: true,
        loadOrderBloon: true,
        pageOrder: '',
        nomoreOrder: true,
        clickTimes: 1
      })
    }else{
      that.setData({
        icon_free: base.static + 'collage/free1.png',
        icon_myFree: base.static + 'collage/myFree2.png',
        current: current,
      })
      if (that.data.clickTimes == 1) {
        that.setData({
          clickTimes: 2
        })
        that.collageorderlist(1)
      }
    }
  },
  //阻止swipeer手滑
  stopTouchMove: function(){
    return false
  },
  // 去首页
  goStore: function () {
    Router.go('store', `store_id=${this.data.store_id}`)
  },
  // 去规则
  goWeb: function(){
    let url = encodeURIComponent('https://kpxd.zhengdianhaohuo.com/h5/#/active/win3_790')
    Router.go('web', `url=${url}`)
  },
  //去订单详情
  goorders(e){
    let orid = e.currentTarget.dataset.orid
    Router.go('orderDetail', `orid=${orid}`);
  },
  //去免费拿详情
  goFreeDetail: function(e){
    let that = this;
    Router.go("free", `store_id=${e.currentTarget.dataset.bslnid}&ceorid=${e.currentTarget.dataset.ceorid}`);
    let p = getCurrentPages().pop();
    Record.clickButton(p, 'Invitation_free')
  },
  //去创建订单页面
  gosubaddress(e){
    let ceorid = e.target.dataset.ceorid;
    Router.go('subaddress', `ceorid=${ceorid}`);
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    if (that.data.current == 1){
      that.scrollTimer = setTimeout(() => {
        that.setData({
          scrolltop: e.scrollTop
        })
      }, 500);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this;
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
  onPullDownRefresh: function () {
    let that = this;
    if (that.data.current == 1){
      that.setData({
        goodsList: [], //免费拿
        endFreeBloon: false,
        loadFreeBloon: true,
        nomoreFree: true,
        hottodyList: [], // 2.12.0今日热销
        endHotBloon: true,
        loadHotBloon: true,
      })
      that.getFreeList(1);
    }else{
      that.data.orderlist.forEach((item,index)=>{
        if (item.timmer) {
          clearTimeout(item.timmer)
         }
      })
      that.setData({
        orderlist: [], //我的免费拿
        endOrderBloon: false,
        loadOrderBloon: true,
        pageOrder: '',
        nomoreOrder: true,
      });
      that.collageorderlist(1)
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    if (that.data.current == 1 && that.data.loadFreeBloon && that.data.endFreeBloon) { //免费拿列表
      that.setData({
        endFreeBloon: false
      })
      that.getFreeList(that.data.pageFree);
    } else if (that.data.current == 1 && that.data.loadHotBloon && that.data.endHotBloon) {//今日热销
      that.setData({
        endHotBloon: false
      })
      that.storeListHot(that.data.pageHot);
    } else if (that.data.current == 2 && that.data.loadOrderBloon && that.data.endOrderBloon) {//我的免费拿
      that.data.orderlist.forEach((item, index) => {
        if (item.timmer) {
          clearTimeout(item.timmer)
        }
      })
      that.setData({
        endOrderBloon: false
      })
      that.collageorderlist(that.data.pageOrder);
    }
  },
})